package com.coolcode.util;

import com.coolcode.entity.UserInfo;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.TextCodec;

import java.util.Date;
import java.util.UUID;

public class JWTUtil {

    private static final String secretKey = "admin";
    private static final String base64EncodedSecretKey = TextCodec.BASE64.encode(secretKey.getBytes());

    public static String generateToken(UserInfo userInfo, long expireTime) {
        JwtBuilder builder = Jwts.builder();
        return builder
                // header
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                // payload
                .claim("username", userInfo.getUserName())
                .setExpiration(new Date(System.currentTimeMillis() + expireTime))
                .setId(UUID.randomUUID().toString())
                // signature
                .signWith(SignatureAlgorithm.HS256, base64EncodedSecretKey)
                .compact();
    }

    public static UserInfo parseToken(String jwt) {

        try{
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey(base64EncodedSecretKey).parseClaimsJws(jwt);
            Claims claims = claimsJws.getBody();
            UserInfo userInfo = new UserInfo();
            userInfo.setUserName((String)claims.get("username"));
            return userInfo;
        }catch(JwtException e){
            // handle exception
            throw e;
        }
    }
}
